# -*- coding: utf-8 -*-
import datetime
from dateutil.parser import parse
from faker import Faker
from utils.logger import log


class TestFunction:
    """
    编写一些函数
    """

    def __init__(self):
        self.faker = Faker(locale='zh_CN')

    def city(self):
        """生成随机的城市名称"""
        return self.faker.city()

    def country(self):
        """生成随机的国家名称"""
        return self.faker.country()

    def province(self):
        """生成随机的省份名称"""
        return self.faker.province()

    def word(self):
        """生成单个词语"""
        return self.faker.word()

    def current_month(self):
        """获取当前月，返回格式为：年月"""
        date = datetime.datetime.now()
        month = str(date.year) + date.month if date.month >= 10 else str(
            date.year) + '0' + str(date.month)
        return month

    def today(self):
        """今天,默认格式为年月日"""
        return str(datetime.date.today())

    def str_add(self, *params):
        result = ''
        for param in params:
            result += str(param)
        return result

    def today_end(self, type=''):
        '''今天最后时间,type不为空返回时间戳'''
        if type == '':
            return self.str_add(self.today(), ' 23:59:59')
        else:
            return self.timestamp(self.str_add(self.today(), ' 23:59:59'))

    def date_add_start(self, num, type=''):
        '''通过时间计算后一天的开始时间，type不为空返回时间戳'''
        if type == '':
            return self.str_add(self.date_add(num), ' 00:00:00')
        else:
            return self.timestamp(self.str_add(self.date_add(num), ' 00:00:00'))

    def date_add(self, num, date='', unit='days'):
        """
        计算时间,加法
        :param unit: 单位，如：days、hours等
        :param date: 日期，格式为：%Y-%m-%d %H:%M:%s
        :param num: 天数
        :return:
        """
        temp = dict()
        temp[unit] = num
        # 如果date没传，则默认为今天
        if date == '':
            date = self.today()
        unit_list = ['days', 'seconds', 'microseconds', 'milliseconds', 'minutes', 'hours', 'weeks']
        if unit in unit_list:
            date_value = parse(date) + datetime.timedelta(**temp)
            if date_value.hour == 0 and date_value.minute == 0 and date_value.second == 0:
                return date_value.strftime('%Y-%m-%d')
            else:
                return date_value
        else:
            msg = '单位格式传入错误，可以输入：days, seconds, microseconds,milliseconds, minutes, hours, weeks'
            log.error(msg)
            return date

    def methods(self):
        """获取类中所有的函数名称（除内置函数）"""
        return list(
            filter(lambda m: not m.startswith("__") and not m.endswith("__") and callable(getattr(self, m)), dir(self)))

    def timestamp(self, time):
        """日期并转换成时间戳"""
        time = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
        return int(time.timestamp())

    def curdate(self, num=0, unit='hours'):
        """
        获取当前时间，也可以对时间进行计算
        :param num: 计算的数量
        :param unit: 计算单位，默认为小时
        :return:
        """
        now = datetime.datetime.now()
        format_datetime = now.strftime("%Y-%m-%d %H:%M:%S")
        temp = dict()
        temp[unit] = num
        unit_list = ['days', 'seconds', 'microseconds', 'milliseconds', 'minutes', 'hours', 'weeks']
        if unit in unit_list:
            date_value = parse(format_datetime) + datetime.timedelta(**temp)
            if date_value.hour == 0 and date_value.minute == 0 and date_value.second == 0:
                return date_value.strftime('%Y-%m-%d %H:%M:%S')
            else:
                return date_value
        else:
            msg = '单位格式传入错误，可以输入：days, seconds, microseconds,milliseconds, minutes, hours, weeks'
            log.error(msg)
            return format_datetime


if __name__ == '__main__':
    a = TestFunction()
    print(a.today_end(6))
    print(a.date_add_start(6))
    print(a.date_add_start(6, 1))
    print(a.curdate(1,'hours'))
